﻿using System;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace Bee.Infrastructure
{
    public class HttpHelper
    {
        private static Logger logger = new Logger(typeof(HttpHelper));
        /// <summary>
        /// 获取响应
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static HttpWebResponse GetHttpWebResponse(string url)
        {
            Uri uri = new Uri(url);
            HttpWebRequest webRequest = WebRequest.Create(uri) as HttpWebRequest;
            webRequest.Timeout = 30000;
            webRequest.Method = "GET";
            webRequest.UserAgent = "Mozilla/5.0";
            webRequest.KeepAlive = true;
            webRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
            webRequest.Accept = "text/html";
            try
            {
                return webRequest.GetResponse() as HttpWebResponse;
            }
            catch (WebException ex)
            {
                logger.Error("远程服务器发生错误:"+ex.Message, ex);
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 下载数据字节
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static byte[] DownloadBytes(string url)
        {
            var response = GetHttpWebResponse(url);
            Stream stream = response.GetResponseStream();
            int contentLength = (int)response.ContentLength;
            byte[] bytes = new byte[contentLength];
            int offset = 0;
            while (contentLength > 0)
            {
                int i = stream.Read(bytes, offset, contentLength);
                contentLength -= i;
                offset += i;
            }
            return bytes;
        }

        /// <summary>
        /// 下载html网页
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string DownloadHtml(string url)
        {
            string html = string.Empty;
            var webResponse = GetHttpWebResponse(url);
            //获取目标网站的编码格式
            string contentype = webResponse.Headers["Content-Type"];
            Regex regex = new Regex("charset\\s*=\\s*[\\W]?\\s*([\\w-]+)", RegexOptions.IgnoreCase);
            if (webResponse.ContentEncoding.ToLower() == "gzip")//如果使用了GZip则先解压
            {
                using (Stream streamReceive = webResponse.GetResponseStream())
                {
                    using (var zipStream = new GZipStream(streamReceive, System.IO.Compression.CompressionMode.Decompress))
                    {
                        //匹配编码格式
                        if (regex.IsMatch(contentype))
                        {
                            Encoding ending = Encoding.GetEncoding(regex.Match(contentype).Groups[1].Value.Trim());
                            using (StreamReader sr = new System.IO.StreamReader(zipStream, ending))
                            {
                                html = sr.ReadToEnd();
                            }
                        }
                        else
                        {
                            using (StreamReader sr = new System.IO.StreamReader(zipStream, Encoding.UTF8))
                            {
                                html = sr.ReadToEnd();
                            }
                        }
                    }
                }
            }
            else
            {
                using (Stream streamReceive = webResponse.GetResponseStream())
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(streamReceive, Encoding.Default))
                    {
                        html = sr.ReadToEnd();
                    }
                }
            }
            return html;
        }

    }
}
